package com.sgb.kjwl.view.ui.adapter.transport;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.transport.CarriageInfo;
import com.sgb.kjwl.model.entity.transport.SingleItemConstant;
import com.swgk.core.base.api.ICallBack;
import com.sgb.knowledgeshare.utils.SharePermissionUtils;
import com.sgb.knowledgeshare.view.activity.HomeShareActivity;
import com.sgb.knowledgeshare.view.activity.PlayListActivity;
import com.swgk.core.view.entity.PermissionEntity;
import com.sgb.kjwl.utils.NumberUtil;
import com.swgk.core.util.PermissionCheckUtil;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.view.ui.activity.self.logistics.InquiryActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.widget.RoundImageView;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.base.model.entity.VideoBean;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.DateUtils;
import com.im.immodel.IMUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.StringUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author: 王彬臣
 * @date: 2021/2/28
 * @Description: 竞价找车混合类型adtpter
 */

public class CarriageListMultiTypeAdapter extends BaseMultiItemQuickAdapter<CarriageInfo, BaseViewHolder> {

    public CarriageListMultiTypeAdapter(List<CarriageInfo> data) {
        super(data);
        addItemType(SingleItemConstant.TYPE_ONE, R.layout.item_carrier_list);
        addItemType(SingleItemConstant.TYPE_TWO, R.layout.item_list);
    }

    @Override
    protected void convert(BaseViewHolder helper, CarriageInfo carriageInfo) {
        switch (carriageInfo.getItemType()) {
            case SingleItemConstant.TYPE_ONE:
                TextView title_view = helper.getView(R.id.title_view);
                TextView tv_distance = helper.getView(R.id.tv_distance);
                TextView tiem_view = helper.getView(R.id.tiem_view);
                TextView price_view = helper.getView(R.id.price_view);
                RoundImageView issuer_img = helper.getView(R.id.issuer_img);
                TextView issuer_name = helper.getView(R.id.issuer_name);
                TextView tv_city = helper.getView(R.id.tv_city);
                tv_city.setText(carriageInfo.getShipCityName() + " " + carriageInfo.getShipDistrictName() + " ➞ " + carriageInfo.getDestCityName() + " " + carriageInfo.getDestDistrictName());
                StringBuilder strBuilder = new StringBuilder();
                if (!TextUtils.isEmpty(carriageInfo.getCarNumber())) {
                    strBuilder.append(carriageInfo.getCarNumber());
                }
                if (!TextUtils.isEmpty(carriageInfo.getCarTypeName())) {
                    strBuilder.append("/");
                    strBuilder.append(carriageInfo.getCarTypeName());
                }

                if (!TextUtils.isEmpty(carriageInfo.getCarLenName())) {
                    strBuilder.append("/");
                    strBuilder.append("车长 ").append(carriageInfo.getCarLenName());
                }
                if (!TextUtils.isEmpty(carriageInfo.getWeight())) {
                    strBuilder.append("/");
                    strBuilder.append(NumberUtil.trim0(carriageInfo.getWeight()) + "吨");
                }
                if (!TextUtils.isEmpty(carriageInfo.getHeightHurdle())) {
                    strBuilder.append("/栏高 " + carriageInfo.getHeightHurdle() + "米");
                }
                if (carriageInfo.getIsDump() != null) {
                    strBuilder.append("/");
                    strBuilder.append(getIsDumpStr(carriageInfo.getIsDump()));
                }
                title_view.setText(strBuilder.toString());
                if (carriageInfo.getShipmentEndTime() == 0 ||
                        DateUtils.stampToDay4(String.valueOf(carriageInfo.getShipmentStartTime())).equals(DateUtils.stampToDay4(String.valueOf(carriageInfo.getShipmentEndTime())))) {
                    tiem_view.setText("可装货时间:" + DateUtils.stampToDay5(String.valueOf(carriageInfo.getShipmentStartTime())));
                } else {
                    tiem_view.setText("可装货时间:" + DateUtils.stampToDay5(String.valueOf(carriageInfo.getShipmentStartTime())) + " - " +
                            DateUtils.stampToDay5(String.valueOf(carriageInfo.getShipmentEndTime())));
                }

                if (TextUtils.isEmpty(carriageInfo.getDistance())) {
                    tv_distance.setText("");
                } else {
                    tv_distance.setText(Double.valueOf(carriageInfo.getDistance()) < 1000 ? "距您1km以内" : "距您" + StringUtil.fromatUpDistance(carriageInfo.getDistance()) + "km");
                }

                if (carriageInfo.getDiscuss() != null && carriageInfo.getDiscuss() == 1) {
                    price_view.setText("意向运费：商议");
                } else {
                    String kms = "";
                    if (carriageInfo.getKilometre() != null && carriageInfo.getKilometre() > 0) {
                        kms = NumberUtil.trim0(carriageInfo.getKilometre()) + "公里内";
                    }
                    price_view.setText("意向运费：" + kms + NumberUtil.trim0(carriageInfo.getFreight()) + carriageInfo.getFreightUnit());
                }

                if (!TextUtils.isEmpty(carriageInfo.getRoleName())) {
                    issuer_name.setText(carriageInfo.getRoleName());
                }

                if (carriageInfo.getTerminal() != null) {
                    int resId = R.drawable.geren_person_touxiang;
                    switch (carriageInfo.getTerminal()) {
                        case 1:
                            resId = R.mipmap.icon_company_default;
                            break;
                        case 2:
                            resId = R.mipmap.icon_team_default_1;
                            break;
                        case 3:
                            resId = R.drawable.geren_person_touxiang;
                            break;
                    }

                    if (!TextUtils.isEmpty(carriageInfo.getImg()))
                        Glide.with(mContext)
                                .load(carriageInfo.getImg())
                                .placeholder(resId)
                                .error(resId)
                                .into(issuer_img);
                    else
                        issuer_img.setImageResource(resId);
                }

                helper.getView(R.id.ll_phone).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                            VerificationCodeLoginActivity.start(mContext);
                        } else {
                            if (!TextUtils.isEmpty(carriageInfo.getContrctsNumber())) {
                                new RoundDialog.Builder(mContext)
                                        .title("确认呼叫")
                                        .content(carriageInfo.getContrctsNumber())
                                        .confirm("确定")
                                        .cancelable(false)
                                        .confirmCallback(view -> {
                                            Intent intent = new Intent(Intent.ACTION_DIAL);
                                            Uri data = Uri.parse("tel:" + carriageInfo.getContrctsNumber());
                                            intent.setData(data);
                                            mContext.startActivity(intent);
                                        })
                                        .show();
                            } else {
                                ToastUtil.show(mContext, "无电话号码");
                            }
                        }
                    }
                });
                //询价
                helper.getView(R.id.ll_inquiry).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (UserOperating.getInstance().isNotLogged(mContext)) {
                            return;
                        }
                        if (carriageInfo != null && !UserOperating.getInstance().IsAuth(mContext, carriageInfo.getAuthTime())) {
                            return;
                        }
                        refresh(carriageInfo);
                    }
                });
                //交流
                helper.getView(R.id.ll_chat).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (UserOperating.getInstance().isNotLogged(mContext)) {
                            return;
                        }
                        if (carriageInfo != null && !UserOperating.getInstance().IsAuth(mContext, carriageInfo.getAuthTime())) {
                            return;
                        }
                        if (carriageInfo == null || TextUtils.isEmpty(carriageInfo.getCarrierCreateIm())) {
                            return;
                        }

                        IMUtils.getInstance().buildSingleTalking(carriageInfo.getCarrierCreateIm());
                    }
                });
                break;
            case SingleItemConstant.TYPE_TWO:
                bindVideoInfo(helper, carriageInfo);
                break;
        }

    }

    public void refresh(CarriageInfo carriageInfo) {
        //获取用户数据
        //TODO 接口有时候报错，改为不提示报错内容 Callback
        NewAPIManager.getInstance().getLogisticsAPI().getLogisticsPermissions().enqueue(new ICallBack<BaseEntity<PermissionEntity>>() {

            @Override
            public void onSuccess(BaseEntity<PermissionEntity> data) {
                if(data.isSuccess()){
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COM_TYPE, data.getData().getUserType());
                    UserOperating.getInstance().setUserInfo(data.getData());
                    if (UserOperating.getInstance().isNotOpenFundAccount(mContext, PermissionCheckUtil.KEY_WODEXUNJIA)) {
                        return;
                    }
                    getInquiryPermissions(carriageInfo);
                }
            }
        });
    }

    /**
     * 查询询价权限
     *
     * @param carriageInfo
     */
    public void getInquiryPermissions(CarriageInfo carriageInfo) {
        if (!TextUtils.isEmpty(carriageInfo.getCarrierNo())) {
            NewAPIManager.getInstance().getLogisticsAPI().getInquiryPermissions("", carriageInfo.getCarrierNo()).enqueue(new ICallBack<BaseEntity<Boolean>>() {
                @Override
                public void onSuccess(BaseEntity<Boolean> data) {
                    if(data.isSuccess()){
                        if (data.getData()) {
                            //去询价界面
                            InquiryActivity.startCarriageInquiry(mContext, carriageInfo.getCarrierNo(), carriageInfo.getContrctsNumber());
                        } else {
                            MToast.showToast(mContext, "不能对自己发布的承运进行询价！");
                        }
                    }
                }
            });
        }
    }

    private void bindVideoInfo(BaseViewHolder holder, CarriageInfo goodsInfoEntity) {
        List<VideoBean> videoBeanList = new ArrayList<>();
        videoBeanList.addAll(goodsInfoEntity.getVideoList());
        if (videoBeanList.size() >= 6) {
            VideoBean v = new VideoBean();
            v.setType("查看更多视频");
            videoBeanList.add(v);
        }
        RecyclerView recyclerView = holder.getView(R.id.list_data);
        if (goodsInfoEntity.getVideoList() == null || goodsInfoEntity.getVideoList().size() == 0) {
            recyclerView.setVisibility(View.GONE);
            return;
        }
        recyclerView.setVisibility(View.VISIBLE);
        if (recyclerView.getAdapter() == null) {
            recyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
            GoodsInfoVideoAdapter adapter = new GoodsInfoVideoAdapter(mContext, videoBeanList);
            adapter.setOnItemClick(new AdapterOnItemClick<VideoBean>() {
                @Override
                public void onItemClick(VideoBean homeHostVideoEntity, int position) {
                    if (homeHostVideoEntity.isCheckMoreVideos()) {
                        SharePermissionUtils.getPermissionTwo((Activity) mContext,1);
                    } else {
                        Intent intent = new Intent(mContext, PlayListActivity.class);
                        intent.putExtra(PlayListActivity.VIDEOLISTBEAN, (Serializable) adapter.getDatas());
                        intent.putExtra(PlayListActivity.PSO, position);
                        intent.putExtra(PlayListActivity.VIDEOTYPE, "goods_and_car_video");
                        mContext.startActivity(intent);
                    }
                }

            });
            recyclerView.setAdapter(adapter);
        } else {
            ((GoodsInfoVideoAdapter) recyclerView.getAdapter()).setDatas(videoBeanList);
        }

    }


    public String getIsDumpStr(Integer isdump) {
        switch (isdump) {
            case 0:
                return "非自卸";
            case 1:
                return "自卸";
            default:
                return "";
        }

    }

    public void setDatas(List<CarriageInfo> list) {
        if (list == null) {
            this.mData.clear();
        } else {
            this.mData = list;
        }
        notifyDataSetChanged();
    }
}
